package com.mediacloud.app.newsmodule.fragment.baoliao.api;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.user.net.JSONObjectConvertFactory;
import com.mediacloud.app.user.net.SSLSocketClient;
import com.mediacloud.app.user.net.SignInterceptor;
import com.mediaclound.appfactnet.utils.GETBadInterceptor;
import com.mediacloud.app.util.ProxyUtil;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * @author TXL
 * description :
 */
public class FacadeApi {

    private static ISpiderCmsApi spiderCmsApi;
    private static ISpiderCmsApi spiderCmsApiJson;

    public static ISpiderCmsApi getSpiderCmsApi(Context context) {
        if (spiderCmsApi == null) {
            synchronized (FacadeApi.class) {
                if (spiderCmsApi == null) {
                    initSpiderCmsApi(context.getApplicationContext());
                }
            }
        }
        return spiderCmsApi;
    }

    private static void initSpiderCmsApi(Context context) {
        String baseUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(context).facade;
        if (TextUtils.isEmpty(baseUrl)) {
            Log.e("DataInvokeUtil", "initSpiderCmsApi failed spider_cms is null");
            return;
        }
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.dns(new MyDns());
        ProxyUtil.config(builder);
        builder.protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)));
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).facade,AppFactoryGlobalConfig.getAppServerConfigInfo(context).cdn_facade));
        builder.addInterceptor(interceptor);
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("tenantId", context.getResources().getString(com.mediacloud.app.reslib.R.string.tenantid))
                    .build();
            return chain.proceed(request);
        });
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl + "/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        spiderCmsApi = retrofit.create(ISpiderCmsApi.class);
    }

    public static ISpiderCmsApi getSpiderCmsApiJson(Context context) {
        if (spiderCmsApiJson == null) {
            synchronized (FacadeApi.class) {
                if (spiderCmsApiJson == null) {
                    initSpiderCmsApiJson(context.getApplicationContext());
                }
            }
        }
        return spiderCmsApiJson;
    }

    private static void initSpiderCmsApiJson(Context context) {
        String baseUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(context).facade;
        if (TextUtils.isEmpty(baseUrl)) {
            baseUrl = "http://baidu.com/";
            Log.w("DataInvokeUtil", "initSpiderCmsApi failed spider_cms is null");
//            return;
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).facade,AppFactoryGlobalConfig.getAppServerConfigInfo(context).cdn_facade));
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl + "/")
                .addConverterFactory(new JSONObjectConvertFactory())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        spiderCmsApiJson = retrofit.create(ISpiderCmsApi.class);
    }

    public interface ISpiderCmsApi {


        /**
         * 获取门面数据（文稿点击量、点赞量、评论数等）
         */
        @GET("api/interaction/interactionData")
        Observable<JSONObject> getFaceData(@Query("ids") String ids, @Query("type") int type);


        /**
         * 获取智能推荐数据
         */
        @GET("api/interaction/article/recommendation")
        Observable<JSONObject> getIntelligentRecommend(@Query("deviceId") String deviceId, @Query("userId") String userId, @Query("index") int index, @Query("count") int count, @Query("firstIntoFlag") boolean firstIntoFlag);

        /**
         * 获取智能推荐数据
         */
        @GET("api/interaction/article/recommendation")
        Observable<JSONObject> getIntelligentRecommend(@Query("deviceId") String deviceId, @Query("index") int index, @Query("count") int count, @Query("firstIntoFlag") boolean firstIntoFlag);

        /**
         * 获取智能推荐数据置顶
         */
        @GET("api/interaction/article/top")
        Observable<JSONObject> getIntelligentTop(@Query("tenantId") String tenantId);
    }
}